import Vue from 'vue';
import Router from 'vue-router';
import { routers } from './router';
import { title } from '../libs';
import NProgress from 'nprogress'; // Progress 进度条
import 'nprogress/nprogress.css';// Progress 进度条样式
import store from '../store';
import config from '../config';
import APP from '../main';
Vue.use(Router);
// 路由配置
const RouterConfig = {
  mode: 'history',
  routes: routers
};
const router = new Router(RouterConfig);
const Whitelist = ['404', 'login', '403', 'ssologin'];

router.beforeEach((to, from, next) => {
  NProgress.start();
  title(to.meta.title);
  if (Whitelist.indexOf(to.name) >= 0) {
    return next();
  }
  // 登录判断

  store.dispatch('getuser').then(() => {
    // 权限判断
    let isAllow = isMenuPower(to);

    if (!isAllow) {
      return next('/403');
    }
    next();
  }).catch((error) => {
    if (error.message === 'nophplogin') {
      APP.$SSO.Redirect(config.system.SSORedirectlUrl);
    } else if (error.message === 'apiError') {
      APP.$SSO.Redirect(config.system.SSORedirectlUrl);
      APP.$notify.error({
        title: '错误',
        message: '获取用户信息异常'
      });
    }
  });
});
router.afterEach(() => {
  NProgress.done(); // 结束Progress
});
export function isMenuPower (to) {
  let isAllow = false;

  if (to.meta && to.meta.authority) {
    return to.meta.authority.indexOf(store.state.user.UserType) > -1;
  } else {
    isAllow = true;
  }
  return isAllow;
}
export default router;
